﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Media;
using Styx.Common;

namespace CustomProtectedItemInstaller
{
    public class Updater
    {
        private const string SvnUrl = "https://gs-svn.googlecode.com/svn/trunk/HBPlugins/CustomProtectedItemInstaller/";

        private static readonly Regex LinkPattern = new Regex(@"<li><a href="".+"">(?<ln>.+(?:..))</a></li>",
                                                               RegexOptions.CultureInvariant);

        public static bool CheckForUpdate()
        {
            try
            {
                CP2I.Cp2ILog(Colors.DarkSalmon, "Checking for new version");
                var remoteRev = GetRevision();
                if (CP2ISettings.Instance.CurrentRevision != remoteRev &&
                    CP2ISettings.Instance.CurrentRevision < remoteRev)
                {
                    CP2I.Cp2ILog(Colors.DarkSalmon, "A new version was found, downloading Update...");
                    DownloadFilesFromSvn(new WebClient(), SvnUrl);
                    CP2I.Cp2ILog(Colors.DarkSalmon, "Download complete.");
                    CP2ISettings.Instance.CurrentRevision = remoteRev;
                    CP2ISettings.Instance.Save();
                    CP2I.Cp2ILog(Colors.DarkSalmon, "A new version of CP2I has been installed");

                    return true;
                }
                CP2I.Cp2ILog(Colors.Gold, "No updates found");
            }
            catch (Exception ex)
            {
                CP2I.Cp2ILog(Colors.Red, ex.ToString());
            }

            return false;
        }

        private static int GetRevision()
        {
            var client = new WebClient();
            string html = client.DownloadString(SvnUrl);
            var pattern = new Regex(@" - Revision (?<rev>\d+):", RegexOptions.CultureInvariant);
            Match match = pattern.Match(html);
            if (match.Success && match.Groups["rev"].Success)
                return int.Parse(match.Groups["rev"].Value);
            throw new Exception("Unable to retreive revision");
        }

        private static void DownloadFilesFromSvn(WebClient client, string url)
        {
            string html = client.DownloadString(url);
            MatchCollection results = LinkPattern.Matches(html);

            IEnumerable<Match> matches = from match in results.OfType<Match>()
                                         where match.Success && match.Groups["ln"].Success
                                         select match;
            foreach (Match match in matches)
            {
                string file = RemoveXmlEscapes(match.Groups["ln"].Value);
                string newUrl = url + file;

                string filePath = Path.Combine(Path.Combine(Utilities.AssemblyDirectory, @"Plugins\CustomProtectedItemInstaller\"), file);
                CP2I.Cp2ILog(Colors.BlanchedAlmond, "Downloading " + file);
                client.DownloadFile(newUrl, filePath);
            }
        }

        private static string RemoveXmlEscapes(string xml)
        {
            return
                xml.Replace("&amp;", "&").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&quot;", "\"").Replace(
                    "&apos;", "'");
        }

    }
}
